import { useState } from 'react';
import { useReducer, createContext, useContext } from 'react';

const Context = createContext({}); //创建Context，管理共享数据

const defaultState = {
  total: 0, //总数
};

function reducer(state = defaultState, action) {
  ///reducer负责操作数据
  if (action.type === 'add') {
    return { ...state, total: state.total + 1 };
  }
  return state;
}

//父组件
function Father() {
  const [store, dispatch] = useReducer(reducer, defaultState); //创建reducer

  return (
    // 通过 state传递上下文 状态
    <Context.Provider value={{ store, dispatch }}>
      <Counter shop={'一'} />
      <Counter shop={'二'} />
    </Context.Provider>
  );
}
//子组件
function Counter(props) {
  const [count, setCount] = useState(0);
  const { store, dispatch } = useContext(Context);
  console.log(store);

  const add = () => {
    dispatch({ type: 'add' });
    setCount(count + 1);
  };
  return (
    <div>
      <h3>
        面馆{props.shop}：{count}碗面
      </h3>
      <h4>{`总共发行${store.total}碗面`}</h4>
      <button onClick={add} style={{ height: '40px' }}>
        加一碗
      </button>
    </div>
  );
}

export default Father;
